package com.snowher.play.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: by HeJingzhou on 2018/9/25 13:56.
 * <p>
 * Company: 北京天创时代信息技术有限公司
 * <p>
 * Email: tcowork@163.com
 * <p>
 * 应用:
 *
 * @author 贺景洲
 */
public class JwtUtils {

    static Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    /**
     * 创建生成Token
     *
     * @param userId 用户ID
     * @return token
     */
    public static String createToken(String userId) {
        Map<String, Object> claims = new HashMap<>(16);
        claims.put("userId", userId);
        claims.put("userPermission", "admin");
        Date currDate = new Date();
        long currTime = currDate.getTime();
        //保持存活一小时
        long keepOnlineTime = 1000 * 60 * 1;
        Date expDate = new Date(currTime + keepOnlineTime);
        String jws = Jwts.builder()
                .setClaims(claims)
                .setSubject("Joe")
                .setIssuer("HeJingzhou")
                .setIssuedAt(currDate)
                .setExpiration(expDate)
                .signWith(key).compact();
        return jws;
    }

    /**
     * 解析Token
     *
     * @param jws
     */
    public static String parser(String jws) {
        Jws<Claims> claimsJws = null;
        try {
            claimsJws = Jwts.parser().setSigningKey(key).parseClaimsJws(jws);
        } catch (ExpiredJwtException e) {
            e.printStackTrace();
        } catch (UnsupportedJwtException e) {
            e.printStackTrace();
        } catch (MalformedJwtException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        if (claimsJws == null) {
            //过期或者仿造
            return "";
        }

        Claims body = claimsJws.getBody();
        System.out.println("用户ID：" + body.get("userId"));
        System.out.println("发布时间：" + body.getIssuedAt());
        System.out.println("过期时间：" + body.getExpiration());
        System.out.println("发布者：" + body.getIssuer());
        System.out.println("标题：" + body.getSubject());
        System.out.println("权限：" + body.get("userPermission"));
        return body.get("userId").toString();
    }

    public static void main(String[] args) {
        String token = createToken("123");
        parser(token);
    }
}
